import React, { useState } from 'react';
import './TimeRangeSelector.css';

const TimeRangeSelector = ({ onTimeRangeChange }) => {
  const [customRange, setCustomRange] = useState(false);
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');

  // 预设时间范围选项
  const timeRanges = [
    { label: '最近24小时', value: '1d' },
    { label: '最近3天', value: '3d' },
    { label: '最近一周', value: '1w' },
    { label: '最近一月', value: '1m' },
    { label: '自定义', value: 'custom' }
  ];

  const handleRangeSelect = (range) => {
    if (range === 'custom') {
      setCustomRange(true);
      return;
    }

    setCustomRange(false);
    const end = new Date();
    let start = new Date();

    switch (range) {
      case '1d':
        start.setDate(start.getDate() - 1);
        break;
      case '3d':
        start.setDate(start.getDate() - 3);
        break;
      case '1w':
        start.setDate(start.getDate() - 7);
        break;
      case '1m':
        start.setMonth(start.getMonth() - 1);
        break;
      default:
        break;
    }

    onTimeRangeChange({
      start: start.toISOString(),
      end: end.toISOString()
    });
  };

  const handleCustomRangeSubmit = () => {
    if (startDate && endDate) {
      onTimeRangeChange({
        start: new Date(startDate).toISOString(),
        end: new Date(endDate).toISOString()
      });
    }
  };

  return (
    <div className="time-range-selector">
      <div className="preset-ranges">
        {timeRanges.map(({ label, value }) => (
          <button
            key={value}
            className={`range-button ${!customRange && value === '1w' ? 'active' : ''}`}
            onClick={() => handleRangeSelect(value)}
          >
            {label}
          </button>
        ))}
      </div>

      {customRange && (
        <div className="custom-range">
          <input
            type="datetime-local"
            value={startDate}
            onChange={(e) => setStartDate(e.target.value)}
            placeholder="开始时间"
          />
          <span>至</span>
          <input
            type="datetime-local"
            value={endDate}
            onChange={(e) => setEndDate(e.target.value)}
            placeholder="结束时间"
          />
          <button onClick={handleCustomRangeSubmit}>确定</button>
        </div>
      )}
    </div>
  );
};

export default TimeRangeSelector; 